import axios from 'axios'
axios.defaults.baseURL="http://127.0.0.1:8000"
axios.defaults.timeout = 1000*100

axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.put ['Content-Type'] = 'application/json';

axios.interceptors.request.use(
    config =>{
        const token = sessionStorage.getItem("jwt_token")
        console.log(token);
        if(token){
            config.headers.Authorization = 'JWT '+ token
        }
        return config;
    },
    error =>{
        return Promise.error(error)
    })


axios.interceptors.response.use(
    res=> res.status ===200 ? Promise.resolve(res) :Promise.reject(res),
    error =>{
        if (error.response){
            console.log(error.response)
            if (error.response.status===401){
                window.location.href ="http://localhost:8080/#/mdlogn"
            }else{
                return Promise.reject(error.response)
            }
        }else{
            return Promise.reject(error.response)
        }
    });




export function axios_get(url,params){
    return new Promise(
        (resolve,reject)=>{
            axios.get(url,{params:params})
            .then(res=>{
                resolve(res.data)
            }).catch(err=>{
                reject(err.data)
            })
        }
    )
}

export function axios_post(url,data){
    return new Promise(
        (resolve,reject)=>{
            axios.post(url,JSON.stringify(data))
            .then(res=>{
                resolve(res.data)
            }).catch(err=>{
                reject(err.data)
            })
        }
    )
}

export function axios_put(url,data){
    return new Promise(
        (resolve,reject)=>{
            axios.put(url,JSON.stringify(data))
            .then(res=>{
                resolve(res.data)
            }).catch(err=>{
                reject(err.data)
            })
        }
    )
}

export function axios_delete(url,params){
    return new Promise(
        (resolve,reject)=>{
            axios.delete(url,{params:params})
            .then(res=>{
                resolve(res.data)
            }).catch(err=>{
                reject(err.data)
            })
        }
    )
}




